package com.qd.pay.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.pay.domain.OrderReportNotifyErrorDTO;
import com.qd.pay.model.OrderReportNotifyError;
import com.qd.pay.repository.OrderReportNotifyErrorRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @author sjk
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrderReportNotifyErrorService {

    private final OrderReportNotifyErrorRepository orderReportNotifyErrorRepository;
    @Resource
    private RedisTemplateUtil<OrderReportNotifyError> redisTemplateUtil;

    private static final String PREFIX_ID = "m_order_report_notify_error_eid_{0}";

    @Transactional(rollbackFor = Exception.class)
    public OrderReportNotifyError save(OrderReportNotifyError model) throws ApiException {
        try {
            if (!orderReportNotifyErrorRepository.save(model)) {
                throw new ApiException(ApiResult.error());
            }
            return model;
        } finally {
            clearCache(model);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(OrderReportNotifyError model) throws ApiException {
        final OrderReportNotifyError historyModel = Optional.ofNullable(getById(model.getEid())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        try {
            if (!orderReportNotifyErrorRepository.updateById(model)) {
                throw new ApiException(ApiResult.error());
            }
            return true;
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean removeById(String eid) throws ApiException {
        final OrderReportNotifyError historyModel = Optional.ofNullable(getById(eid)).orElseThrow(() -> new ApiException("ID不存在,不能删除"));
        try {
            if (!orderReportNotifyErrorRepository.removeById(eid)) {
                throw new ApiException(ApiResult.error());
            }
            return true;
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    public Boolean isExists(String eid) {
        return orderReportNotifyErrorRepository.isExists(eid);
    }

    public OrderReportNotifyError getById(String eid) {
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, eid);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY * 3), () -> orderReportNotifyErrorRepository.getById(eid), OrderReportNotifyError.class);
    }

    public IPage<OrderReportNotifyErrorDTO> page(Page<OrderReportNotifyErrorDTO> page, QueryWrapper<OrderReportNotifyError> queryWrapper) {
        IPage<OrderReportNotifyError> iPage = orderReportNotifyErrorRepository.page(page.convert(this::dtoToModel), queryWrapper);
        return iPage.convert(this::modelToDto);
    }


    private void clearCache(OrderReportNotifyError model) {
        if (null == model) {
            return;
        }
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getEid());
        redisTemplateUtil.deleteByKey(key);
    }

    public OrderReportNotifyErrorDTO modelToDto(OrderReportNotifyError model) {
        if (null == model) {
            return null;
        }
        OrderReportNotifyErrorDTO dto = new OrderReportNotifyErrorDTO();
        dto.setEid(model.getEid());
        dto.setOrderId(model.getOrderId());
        dto.setOutTradeNo(model.getOutTradeNo());
        dto.setThirdPartyOrder(model.getThirdPartyOrder());
        dto.setNotifyUrl(model.getNotifyUrl());
        dto.setNotifyBody(model.getNotifyBody());
        dto.setErrCount(model.getErrCount());
        dto.setAddTime(model.getAddTime());
        model.freeData();
        return dto;
    }

    public OrderReportNotifyError dtoToModel(OrderReportNotifyErrorDTO dto) {
        if (null == dto) {
            return null;
        }
        OrderReportNotifyError model = new OrderReportNotifyError();
        model.setEid(dto.getEid());
        model.setOrderId(dto.getOrderId());
        model.setOutTradeNo(dto.getOutTradeNo());
        model.setThirdPartyOrder(dto.getThirdPartyOrder());
        model.setNotifyUrl(dto.getNotifyUrl());
        model.setNotifyBody(dto.getNotifyBody());
        model.setErrCount(dto.getErrCount());
        model.setAddTime(dto.getAddTime());
        dto.freeData();
        return model;
    }

    @Transactional(readOnly = true)
    public List<OrderReportNotifyError> getList(QueryWrapper<OrderReportNotifyError> queryWrapper) {
        return orderReportNotifyErrorRepository.getBaseMapper().selectList(queryWrapper);
    }
}